package com.ken.astroboy.robot;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ken.astroboy.core.Constant;

public class MoLiRobot implements Robot {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private String apiUrl;
	private CloseableHttpClient httpClient;

	public MoLiRobot() {
		String api_key = Constant.itpkApiKey;
		String api_secret = Constant.itpkApiSecret;
		if(StringUtils.isNotBlank(api_key) && StringUtils.isNotBlank(api_secret)){
			this.apiUrl = Constant.ITPK_API + "?api_key=" + api_key + "&api_secret=" + api_secret;
		}
		
		RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();	
		httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
	}

	@Override
	public String talk(String msg) {
		
		String result = "";
				
		if(this.apiUrl == null){
			logger.info("茉莉机器人未在config.properties中配置");
		}else{
			String url = apiUrl + "&question=" + msg;
			
			CloseableHttpResponse response = null;
			
			try {
				
				HttpGet httpGet = new HttpGet(url);
				
				logger.debug(httpGet.getRequestLine().toString());
				
				response = httpClient.execute(httpGet);
				
				logger.debug(response.toString());
				
				int statusCode = response.getStatusLine().getStatusCode();
				
				if (statusCode == HttpStatus.SC_OK) {
					HttpEntity entity = response.getEntity();
					result = EntityUtils.toString(entity, Constant.encoding);
					logger.info("茉莉机器人回复：[{}]",result);		    
				}
			} catch (Exception e) {
				logger.info("茉莉机器人调用有异");
			} finally {
				try {
					response.close();
				} catch (IOException e) {
					logger.info("茉莉机器人调用有异");
				}
			}			
		}	
		return result;
	}

}
